from flask import Flask,session
from flask_wtf import CSRFProtect
from flask_session import Session #注意这个Session,作用：将app和Session关联，config里面配置的也是这个Session的参数
from config import config,Config
from flask_sqlalchemy import SQLAlchemy
import logging
from logging.handlers import RotatingFileHandler
from redis import StrictRedis
from flask_wtf import csrf

db = SQLAlchemy()

redis_store = StrictRedis(host=Config.REDIS_HOST,port=Config.REDIS_PORT,decode_responses=True)

def set_log(config_name):
    logging.basicConfig(level=config[config_name].LOG_LEVEL)
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    file_log_handler.setFormatter(formatter)
    logging.getLogger().addHandler(file_log_handler)

# 工厂化一个app,包括：1.实例化app并加载配置, 2.csrf, 3.session,4.注册蓝图,5.日志
def create_app(config_name):
    app = Flask(__name__)
    set_log(config_name)
    app.config.from_object(config[config_name])
    db.init_app(app)

    Session(app)
    CSRFProtect(app)

    @app.after_request
    def after_request(response):
        csrf_token = csrf.generate_csrf()
        response.set_cookie('csrf_token', csrf_token)
        return response

    # 注册  第一个参数 视图名称 第二个参数 过滤器名称
    from info.utils.common import index_class
    app.add_template_filter(index_class,'index_class')

    from info.modules.news import news_blu
    app.register_blueprint(news_blu)

    from info.modules.passport import passport_blue
    app.register_blueprint(passport_blue)

    from info.modules.profile import profile_blu
    app.register_blueprint(profile_blu)

    from info.modules.admin import admin_blue
    app.register_blueprint(admin_blue)

    return app


'''
初始化模块：
调用后返回一个怎样的app?

                创建一个app并增加各种功能：
                配置了日志信息
                加载了基础配置数据
                设置了session
                设置了csrf跨站保护
                注册了蓝图函数     *************************** absolutely

'''